// 登录页面逻辑
const userApi = require('../../api/userApi');
const app = getApp();

Page({
  data: {
    loading: false
  },

  onLoad: function (options) {
    // 页面初始化
  },

  // 处理登录
  handleLogin: function () {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    wx.login({
      success: (res) => {
        if (res.code) {
          // 发送 res.code 到后台换取 token
          userApi.login(res.code)
            .then(result => {
              // 保存token
              app.globalData.token = result.token;
              app.globalData.isLoggedIn = true;
              
              if (result.isPhoneBound) {
                // 已绑定手机号，获取用户信息
                return userApi.getUserInfo();
              } else {
                // 未绑定手机号，跳转到绑定页面
                wx.navigateTo({
                  url: '/pages/phone-bind/phone-bind'
                });
                throw new Error('需要绑定手机号');
              }
            })
            .then(userInfo => {
              // 保存用户信息
              app.globalData.userInfo = userInfo;
              app.globalData.points = userInfo.points || 0;
              
              // 跳转到首页
              wx.switchTab({
                url: '/pages/home/home'
              });
            })
            .catch(err => {
              console.error('登录失败', err);
              if (err.message !== '需要绑定手机号') {
                wx.showToast({
                  title: '登录失败，请重试',
                  icon: 'none'
                });
              }
            })
            .finally(() => {
              this.setData({ loading: false });
            });
        } else {
          this.setData({ loading: false });
          wx.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  
  // 显示用户协议
  showAgreement: function () {
    wx.navigateTo({
      url: '/pages/agreement/agreement'
    });
  },
  
  // 显示隐私政策
  showPrivacy: function () {
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    });
  }
}); 